<template>
    <div>
        <el-form label-width="110px" size="small">
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="产品代码:">
                        <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="委托方向:">
                        <el-select v-if="notMesh" v-model="instruction.orderDirection" size="mini" disabled>
                            <el-option value="E" label="基金转换"></el-option>
                        </el-select>
                        <el-select v-else v-model="instruction.orderDirection" size="mini">
                            <el-option
                                v-for="i in orderDirectionSelectData"
                                :key="i.dictKey"
                                :label="i.dictKey + ' ' + i.dictKeyName"
                                :value="i.dictKey"
                                :style="handleTextColor(i.dictKey)"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="转出组合编号:">
                        <el-select v-model="instruction.fundAccountCode" size="mini">
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                :value="i.fundAccountCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="转入组合编号:">
                        <el-select v-model="instruction.destCombiId" size="mini" @change="handleDestCombiIdChange">
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                :value="i.fundAccountCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="转出证券代码:">
                        <el-select
                            ref="searchSelect"
                            size="mini"
                            clearable
                            filterable
                            :filter-method="getOutStockCodeList"
                            :loading="selectLoading"
                            v-model="instruction.stockCode"
                            @change="handleStockCode"
                            @focus="selectFocus($event, 'out')"
                            @clear="getOutStockCodeList('')"
                        >
                            <el-option
                                v-for="i in outStockCodeSelectData"
                                :key="i.stockCode"
                                :label="i.stockCode + ' ' + i.stockNameSt"
                                :value="i.stockCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="转入证券代码:">
                        <el-select
                            ref="searchSelect"
                            size="mini"
                            clearable
                            filterable
                            :filter-method="getIntoStockCodeList"
                            :loading="selectLoading"
                            v-model="instruction.destSecurityCode"
                            @change="handleIntoStockCode"
                            @focus="selectFocus($event, 'into')"
                            @clear="getIntoStockCodeList('')"
                        >
                            <el-option
                                v-for="i in intoStockCodeSelectData"
                                :key="i.stockCode"
                                :label="i.stockCode + ' ' + i.stockNameSt"
                                :value="i.stockCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="业务类型:">
                        <el-select v-model="instruction.businessType" size="mini" disabled>
                            <el-option value="A" label="开放式基金"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="巨额赎回标志:">
                        <el-select v-model="instruction.bulkType" size="mini">
                            <el-option v-for="i in bulkTypeSelectData" :key="i.dictKey" :label="i.dictKeyName" :value="i.dictKey"> </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="转换份额:">
                        <RiskInputNumber
                            :input="instruction.orderAmount"
                            :inputAfter="'份'"
                            :precision="2"
                            :maxlength="15"
                            :field="'orderAmount'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>
<script lang="ts">
import Invest from '@/common/dict/invest';
import { objToArr, SGU_CACHE } from '@/utils/diction-const-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import { handleTextColor } from '@/utils/tools';

@Component({
    name: 'FundTransferForm',
    components: {
        RiskInputNumber,
        RiskEntryInput,
    },
})

// 基金转换指令表单
export default class FundTransferForm extends Vue {
    @Prop()
    detail: any;
    @Prop()
    outStockInfo: any;
    @Prop()
    intoStockInfo: any;
    @Prop()
    notMesh: boolean;
    @Prop()
    renderCountKey: number;
    handleTextColor = handleTextColor;
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据

    // 巨额赎回下拉数据
    bulkTypeSelectData: any[] = [
        { dictKey: '1', dictKeyName: '撤销' },
        { dictKey: '2', dictKeyName: '顺延' },
    ];

    orderDirectionSelectData: any[] = [
        {
            dictKey: 'D',
            dictKeyName: '基金认购',
        },
        {
            dictKey: 'p',
            dictKeyName: '开基申购',
        },
        {
            dictKey: 'q',
            dictKeyName: '开基赎回',
        },
        {
            dictKey: 'E',
            dictKeyName: '基金转换',
        },
    ];
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态

    instruction = {
        fundCode: '', // 产品代码
        fundAccountCode: '', // 转出组合编号
        destCombiId: '', // 转入组合编号
        destCombiName: '', // 转入组合名称
        reportCode: '', // 申报代码
        orderDirection: 'E', // 委托方向
        stockCode: '', // 证券代码
        destSecurityCode: '', // 转入证券代码
        destSecurityName: '', // 转入证券名称
        businessType: 'A',
        businessTypeName: '',
        orderPrice: '',
        orderAmount: '',
        orderBalance: '', // 指令金额
        opponentCode: '',
        bulkType: '1', // 巨额赎回
        marketCode: '',
        fundNameSt: '',
        fundAccountName: '',
        assetCode: '',
        assetName: '',
    };
    stockInfo: any = {};
    // intoStockInfo: any = {};
    intoStockCodeSelectData: any[] = [];
    outStockCodeSelectData: any[] = [];
    stockInfo2: any = {};

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        if (this.detail && this.detail.instruction) {
            this.instruction.fundAccountCode = this.detail.instruction.fundAccountCode;
        } else {
            if (newData && newData.length) {
                this.instruction.fundAccountCode = newData[0].fundAccountCode;
            }
        }
    }

    @Watch('instruction', { immediate: true, deep: true })
    setValues() {
        this.$emit('handleSettingValue', this.instruction, '8');
    }

    @Watch('outStockInfo', { immediate: true, deep: true })
    onWatchStockInfo() {
        if (this.outStockInfo) {
            console.log(this.outStockInfo, 'this.outStockInfo');

            this.stockInfo = this.outStockInfo;
            this.instruction.orderPrice = this.outStockInfo?.lastPrice;
            this.instruction.stockCode = this.outStockInfo?.stockCode;
            this.calOrderBalance();
            if (this.instruction.stockCode) {
                this.instruction.reportCode = this.outStockInfo?.stockCode.split(' ')[0] || '';
            }
            this.getOutStockCodeList(this.outStockInfo?.stockCode);
        }
    }

    // @Watch('intoStockInfo', { immediate: true, deep: true })
    // onWatchIntoStockInfo() {
    //     if (this.intoStockInfo) {
    //         console.log(this.intoStockInfo);

    //         this.stockInfo2 = this.intoStockInfo;
    //         this.instruction.destSecurityCode = this.intoStockInfo.stockCode;
    //         this.instruction.destSecurityName = this.intoStockInfo.stockName;
    //         this.instruction.marketCode = this.intoStockInfo.marketCode;
    //         this.getIntoStockCodeList(this.intoStockInfo?.stockCode);
    //     }
    // }

    @Watch('renderCountKey', { immediate: true, deep: true })
    async setForm() {
        if (this.detail && Object.keys(this.detail).length) {
            let instruction: any = {};
            // 获取组合编码下拉框数据
            let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
            arr.forEach(item => {
                this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
            });
            for (const key in this.detail) {
                instruction[key] = this.detail[key];
            }
            // this.instruction = JSON.parse(JSON.stringify(this.detail));
            console.log(this.instruction, 'this.instruction');

            // 巨额赎回标志默认为撤销
            instruction.bulkType = this.detail.bulkType || '1';

            // 指令修改回显
            if (this.detail.instNo) {
                // 组合编码
                instruction.fundAccountCode = this.detail.groupCode;
                // 组合名称
                instruction.fundAccountName = this.detail.groupName;
            }
            if (instruction.stockCode) {
                instruction.reportCode = instruction?.stockCode.split(' ')[0];
            }
            instruction.targetType = '1';

            this.instruction = instruction;

            await this.getIntoStockCodeList(instruction.destSecurityCode);
            await this.getOutStockCodeList(instruction.stockCode);
            this.stockInfo = this.outStockCodeSelectData.find(item => item.stockCode === this.detail.stockCode);
            this.stockInfo2 = this.intoStockCodeSelectData.find(item => item.stockCode === this.detail.destSecurityCode);

            this.$emit('getStockInfo', this.stockInfo, '8');
            this.$emit('getIntoStockInfo', this.stockInfo2, '8');

            // 指令修改回显
            // if (this.detail.instNo) {
            //     // 组合编号
            //     this.instruction.fundAccountCode = this.detail.groupCode;
            //     // 组合名称
            //     this.instruction.fundAccountName = this.detail.groupName;
            //     await this.getOutStockCodeList(this.detail.stockCode);
            //     await this.getIntoStockCodeList(this.detail.destSecurityCode);
            //     console.log(this.detail.stockCode, this.outStockCodeSelectData, 'lll');

            //     this.stockInfo = this.outStockCodeSelectData.find(item => item.stockCode === this.detail.stockCode);
            //     this.stockInfo2 = this.intoStockCodeSelectData.find(item => item.stockCode === this.detail.destSecurityCode);
            //     console.log(this.stockInfo, this.stockInfo2, 'test');

            // this.$emit('getStockInfo', this.stockInfo, '8');
            // this.$emit('getIntoStockInfo', this.stockInfo2, '8');
            // }
            // if (this.instruction.bulkType == '0') {
            //     this.instruction.bulkType = '1';
            // }

            // if (this.instruction.stockCode) {
            //     this.instruction.reportCode = this.instruction?.stockCode.split(' ')[0];
            // } else {
            //     this.instruction.reportCode = '';
            // }
        }
    }

    get computedFundAccountCodeSelectData(): any {
        return this.fundAccountCodeSelectData[this.instruction.fundCode];
    }

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instruction[field] = value;
        this.calOrderBalance();
    }

    async mounted() {
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
    }

    getEntryslist(val: any) {
        if (this.instruction.fundCode == val) {
            return;
        }
        this.instruction.fundCode = val;
        this.handleFundCodeChange(val);
    }

    // 获取可转入证券代码下拉框数据
    async getIntoStockCodeList(val: string | undefined) {
        this.selectLoading = true;
        await this.$axios
            .post('/position/convertibleStock/in', {
                paging: {
                    currentPage: 1,
                    pageSize: 20,
                },
                excludeStockCodes: this.instruction.stockCode ? [this.instruction.stockCode] : [],
                stockNameOrCode: val,
            })
            .then((res: any) => {
                this.intoStockCodeSelectData = res.list || [];
                this.selectLoading = false;
            });
    }

    // 获取可转出证券代码下拉框数据
    async getOutStockCodeList(val: string | undefined) {
        // this.selectLoading = true;
        await this.$axios
            .post('/position/convertibleStock/out', {
                paging: {
                    currentPage: 1,
                    pageSize: 20,
                },
                fundCode: this.instruction.fundCode,
                fundAcCode: this.instruction.fundAccountCode,
                stockNameOrCode: val,
            })
            .then((res: any) => {
                this.outStockCodeSelectData = res.list || [];
                // this.selectLoading = false;
            });
    }

    // stockNameOrCode

    async handleFundCodeChange(val: string) {
        this.instruction.stockCode = '';
        this.instruction.destSecurityCode = '';
        this.instruction.destCombiId = '';
        this.instruction.reportCode = '';

        this.outStockCodeSelectData = [];
        let fund = this.fundCodeSelectData.find(item => item.fundCode === val) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        this.instruction.fundNameSt = fund.fundNameSt;
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
        this.instruction.fundAccountName = fundAccount.fundAccountName;
        this.instruction.assetCode = fundAccount.assetCode;
        this.instruction.assetName = fundAccount.assetName;
        if (val) {
            // 获取证券代码下拉框数据
            // this.getIntoStockCodeList('');
            // this.getOutStockCodeList('');
            // console.log(this.outStockInfo, 'ooo');
            // await this.getOutStockCodeList(this.stockInfo?.stockCode || '');
            // await this.getIntoStockCodeList(this.intoStockInfo?.stockCode || '');
        } else {
            this.instruction.destSecurityCode = '';
            this.instruction.destCombiId = '';
            this.outStockCodeSelectData = [];
        }
    }

    handleDestCombiIdChange(val: string): void {
        let fundAccount = this.fundAccountCodeSelectData[this.instruction.fundCode] || [] || {};
        fundAccount.forEach(ele => {
            if (ele.fundAccountCode === val) {
                this.instruction.destCombiName = ele.fundAccountName;
                this.instruction.assetCode = fundAccount.assetCode;
                this.instruction.assetName = fundAccount.assetName;
            }
        });
    }

    selectFocus(e, param) {
        let value = e.target.value;
        if (param === 'into') {
            if (!value) {
                this.getIntoStockCodeList('');
            }
        } else {
            if (!value) {
                this.getOutStockCodeList('');
            }
        }
    }

    handleStockVisibleChange(val) {
        if (!val) {
        }
    }

    handleStockCode(stockCode: string): void {
        if (stockCode) {
            this.stockInfo = this.outStockCodeSelectData.find(item => item.stockCode === stockCode);
            this.stockInfo.reportCode = this.stockInfo.stockCode.split(' ')[0];
            this.instruction.reportCode = this.stockInfo.stockCode.split(' ')[0];
            this.instruction.marketCode = this.stockInfo.marketCode;
            this.instruction.orderPrice = this.stockInfo.lastPrice;
            this.getIntoStockCodeList('');
            this.calOrderBalance();
        } else {
            this.stockInfo = {};
            this.instruction.reportCode = '';
            this.instruction.orderPrice = '';
            this.instruction.orderBalance = '';
        }
        this.$emit('getStockInfo', this.stockInfo, '8');
    }

    handleIntoStockCode(stockCode: string): void {
        if (stockCode) {
            this.stockInfo2 = this.intoStockCodeSelectData.find(item => item.stockCode === stockCode);
            this.instruction.destSecurityName = this.stockInfo2?.stockName;
        } else {
            this.stockInfo2 = {};
        }
        this.$emit('getIntoStockInfo', this.stockInfo2, '8');
    }

    calOrderBalance() {
        this.instruction.orderBalance = (Number(this.instruction.orderAmount || '0') * Number(this.instruction.orderPrice || '0')).toString();
    }
}
</script>
<style lang="scss" scoped>
.form-row {
    margin-top: 3px;
    .el-form-item--small {
        margin: 0;
        & /deep/ .el-form-item__label {
            color: #575757;
        }
        & /deep/ .el-input__inner {
            height: 28px;
            line-height: 28px;
        }
    }
}
</style>
